const crypto = require('crypto')

module.exports = {
    encrypt: (key, iv, data) => {
        var cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
        var crypted = cipher.update(data, 'utf8', 'binary');
        crypted += cipher.final('binary');
        crypted = Buffer.from(crypted, 'binary').toString('base64');
        return crypted;
    },
    decrypt: (key, iv, crypted) => {
        crypted = Buffer.from(crypted, 'base64').toString('binary');
        var decipher = crypto.createDecipheriv('aes-256-cbc', key, iv);
        var decoded = decipher.update(crypted, 'binary', 'utf8');
        decoded += decipher.final('utf8');
        return decoded;
    },
    formatTime: (date) => {
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        var hour = date.getHours()
        var minute = date.getMinutes()
        var second = date.getSeconds()
        return [year, month, day].map(
            (n) => {
                n = n.toString()
                return n[1] ? n : '0' + n
            }
        ).join('/')
            + ' '
            + [hour, minute, second].map(
                (n) => {
                    n = n.toString()
                    return n[1] ? n : '0' + n
                }
            ).join(':')
    }
}